package com.jh.paymentchannel.service;

//import static org.hamcrest.CoreMatchers.nullValue;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jh.paymentchannel.pojo.XJYCoinBankCode;
import com.jh.paymentchannel.pojo.XJYCoinBindCard;
import com.jh.paymentchannel.pojo.XJYCoinRegister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.business.XJYCoinBankCodeBusiness;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.xjy.Base64Util;
import com.jh.paymentchannel.util.xjy.KeyGenerator;
import com.jh.paymentchannel.util.xjy.PlatService;

import cn.jh.common.utils.DateUtil;
import net.sf.json.JSONObject;

@Controller
@EnableAutoConfiguration
public class XJYCoinpageRequest {

	private static final Logger log = LoggerFactory.getLogger(XJYCoinpageRequest.class);

	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;

	@Autowired
	private XJYCoinBankCodeBusiness xjyCoinBankCodeBusiness;

	@Autowired
	private Util util;

	@Value("${payment.ipAddress}")
	private String ipAddress;

	@Value("${xjycoin.publickey}")
	private String PublicKey;

	@Value("${xjycoin.appid}")
	private String appId;
	
	//private String PublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHd3HpKMRcIkx83Oz3YkQjw7JMgLQ5ZnQXjUAwmAZ6FVlYSPNMKQY7oCY7O9wQo/kOtjmjngIDh6biMVT70eMuNhpl6B0TOyw3v2FqswqhjvNno6LoKWl2la+/O8tHYYDQE4+ncBApCWzMfj7xIqJENElOExnxEqtTlHehv/JxYQIDAQAB";

	//private String appId = "989d801a0544427093be120f11e36f52";

	private String merinnetUrl = "http://39.106.15.18/openapi/api/unionpay/integral/dzero/mer/innet";

	private String openCardUrl = "http://39.106.15.18/openapi/api/unionpay/integral/dzero/open/card/back";

	private String smsUrl = "http://39.106.15.18/openapi/api/unionpay/integral/dzero/consume/sms";

	private String consumeUrl = "http://39.106.15.18/openapi/api/unionpay/integral/dzero/consume";

	private static final Charset UTF_8 = StandardCharsets.UTF_8;

	private String version = "1.0.1";

	private String channelType = "88";

	// 进件接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/xjycoin/register")
	public @ResponseBody Object xjyRegister(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "expiredTime", required = false) String expiredTime,
			@RequestParam(value = "securityCode", required = false) String securityCode
			) throws Exception {
		log.info("开始进入进件接口======");
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询订单信息出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "没有该订单信息");
			return maps;
		}
		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费用
		String extraFee = resultObj.getString("extraFee");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		String amount = resultObj.getString("amount");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询默认结算卡出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "查询默认结算卡有误");
			return maps;
		}

		if (resultObj.isNullObject()) {

			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}
		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		String bankName = resultObj.getString("bankName");
		String phone = resultObj.getString("phone"); // 预留信用卡手机号码
		String idcard = resultObj.getString("idcard");// 身份证号
		String userName = resultObj.getString("userName");// 用户姓名
		
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "查询银行卡信息有误");
			return maps;
		}
		if (resultObj == null) {
			return null;
		}

		String cardName = resultObj.getString("bankName");
		String cardtype = resultObj.getString("cardType");
		
		
		Map<String, String> paramsMap = new HashMap<String, String>();

		paramsMap.put("appId", appId);
		paramsMap.put("channelType", channelType);
		paramsMap.put("version", version);
		paramsMap.put("orderId", ordercode);// 订单号
		paramsMap.put("txnTime", DateUtil.getyyyyMMddHHmmssDateFormat(new Date()));
		paramsMap.put("toAccNo", cardNo);// 收款卡号
		paramsMap.put("phoneNo", phone);// 预留手机号
		paramsMap.put("toBankName", bankName);// 银行名称
		paramsMap.put("toAccType", "PERSONNEL");// 银行卡类型
		paramsMap.put("realName", userName);// 姓名
		paramsMap.put("identityNo", idcard);// 身份证号
		paramsMap.put("t0DrawRate", rate);// 交易扣率

		String t0DrawFee = new BigDecimal(extraFee).multiply(new BigDecimal("100")).setScale(0).toString();
		paramsMap.put("t0DrawFee", t0DrawFee);// 单笔手续费(单位:分)

		Map<String, String> reqData = new HashMap<String, String>();
		try {
			reqData.put("data", Base64Util.encode(
					KeyGenerator.encryptByPublicKey(JSON.toJSONString(paramsMap).getBytes(UTF_8), PublicKey)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		String requestUrl = String.format(merinnetUrl + "/" + channelType + "/" + appId, channelType, appId);
		String jsonString;
		try {
			jsonString = PlatService.postAsString(reqData, requestUrl, UTF_8);
			JSONObject json = jsonObject.fromObject(jsonString);
			String success = json.getString("success");
			String msg = json.getString("msg");
			JSONObject attributes = json.getJSONObject("attributes");
			String insCode = attributes.getString("insCode");

			log.info("jsonString====" + jsonString);
			log.info("json====" + json);
			log.info("success====" + success);
			log.info("msg====" + msg);
			log.info("attributes====" + attributes);
			log.info("insCode====" + insCode);

			if ("true".equals(success) && "SUCCESS".equalsIgnoreCase(msg)) {
				log.info("请求进件接口成功===================");
				XJYCoinRegister xjyCoinRegister = new XJYCoinRegister();
				xjyCoinRegister.setPhone(phone);
				xjyCoinRegister.setBankCard(cardNo);
				xjyCoinRegister.setIdCard(idcard);
				xjyCoinRegister.setInsCode(insCode);
				xjyCoinRegister.setRate(rate);
				xjyCoinRegister.setExtraFee(extraFee);

				try {
					topupPayChannelBusiness.createXJYCoinRegister(xjyCoinRegister);
				} catch (Exception e) {
					log.error("保存用户进件信息失败=====");
					maps.put("resp_code", "failed");
					maps.put("channel_type", "jf");
					maps.put("resp_message", "保存用户进件信息失败");
					return maps;
				}
				log.info("保存用户进件信息成功=====");
				log.info("开始请求绑卡接口====");
				
				//this.xjyCoinTurnToBindCard(request, response, ordercode, expiredTime, securityCode, cardName, cardtype, bankCard);
				
				maps.put("resp_code", "success");
				maps.put("channel_type", "jf");
				maps.put("redirect_url",
						ipAddress + "/v1.0/paymentchannel/topup/toxjycoinbindcard?&ordercode=" + ordercode + "&ipAddress="
								+ ipAddress + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardName, UTF_8.displayName())
								+ "&cardtype=" + URLEncoder.encode(cardtype, UTF_8.displayName()) + "&expiredTime=" + expiredTime
								+ "&securityCode=" + securityCode);
				return maps;
				
				
			} else {
				log.info("用户进件失败====");
				maps.put("resp_code", "failed");
				maps.put("channel_type", "jf");
				maps.put("resp_message", "亲，入网失败啦，请稍后重试");
				return maps;

			}

		} catch (Exception e) {
			log.error("请求进件接口有误===" + e);
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "亲，请求出错啦！请重新发起交易");
			return maps;
		}

	}

	// 绑卡接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/xjycoin/opencard")
	public @ResponseBody Object xjyCoinOpenCard(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "expiredTime", required = false) String expiredTime,
			@RequestParam(value = "securityCode", required = false) String securityCode
			) throws Exception {
		log.info("开始进入绑卡接口======");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "没有该订单信息");
			return map;
		}

		String realamount = resultObj.getString("realAmount");
		String userid = resultObj.getString("userid");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}

		if (resultObj.isNullObject()) {

			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "没有结算卡");
			return map;
		}

		String cardNo = resultObj.getString("cardNo");
		
		// 查询信用卡信息
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		if (resultObj == null) {
			return null;
		}
		String userName = resultObj.getString("userName");
		/** 身份证号 */
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		String bankName = resultObj.getString("bankName");

		// 根据银行名称获取银行编码
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bankcode/getcodebyname";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("name", bankName);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
		} catch (Exception e) {
			log.error("根据银行名称获取银行编码失败");
			maps.put("resp_code", "failed");
			maps.put("resp_message", "根据银行名称获取银行编码失败");
			return maps;
		}
		
		if(bankName.contains("邮")){
			bankName = "中国邮政储蓄银行";
		}
		XJYCoinBankCode bankNoByBankName = xjyCoinBankCodeBusiness.getBankNoByBankName(bankName);
		String bankNo = bankNoByBankName.getBankNo();
		
		XJYCoinRegister xjyCoinRegisterByBankCard = topupPayChannelBusiness.getXJYCoinRegisterByBankCard(cardNo);
		String insCode = xjyCoinRegisterByBankCard.getInsCode();
		
		String before = expiredTime.substring(0, 2);
		String after = expiredTime.substring(2, 4);

		BigDecimal big = new BigDecimal(before);
		BigDecimal times = new BigDecimal("12");

		int compareTo = big.compareTo(times);
		// 如果前两位大于12，,代表是年/月的格式
		if (compareTo == 1) {
			expiredTime = after + before;
		}else {
			expiredTime = before + after;
		}
		
		Map<String, String> paramsMap = new HashMap<String, String>();

		paramsMap.put("appId", appId);
		paramsMap.put("channelType", channelType);
		paramsMap.put("version", version);
		paramsMap.put("orderId", ordercode);//订单号
		paramsMap.put("txnTime", DateUtil.getyyyyMMddHHmmssDateFormat(new Date()));
		paramsMap.put("accNo", bankCard);//信用卡号
		paramsMap.put("phoneNo", phone);//预留手机号
		paramsMap.put("expired", expiredTime);//有效期
		paramsMap.put("cvn2", securityCode);//安全码
		paramsMap.put("realName", userName);//姓名
		paramsMap.put("identityNo", idcard);//身份证号
		paramsMap.put("accattr", "2");//银行卡属性
		paramsMap.put("terminalOpenBankCode", bankNo);//银行代码
		paramsMap.put("insCode", insCode);//入网编号
		
		Map<String, String> reqData = new HashMap<String, String>();
		try {
			reqData.put("data", Base64Util.encode(
					KeyGenerator.encryptByPublicKey(JSON.toJSONString(paramsMap).getBytes(UTF_8), PublicKey)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		String requestUrl = String.format(openCardUrl+"/"+channelType+"/"+appId, channelType, appId);
		String jsonString;
		try {
			jsonString = PlatService.postAsString(reqData, requestUrl, UTF_8);
			JSONObject json = jsonObject.fromObject(jsonString);
			String success = json.getString("success");
			String msg = json.getString("msg");
			JSONObject attributes = json.getJSONObject("attributes");
			String token = attributes.getString("token");
			log.info("jsonString====" + jsonString);
			log.info("json====" + json);
			log.info("success====" + success);
			log.info("msg====" + msg);
			log.info("attributes====" + attributes);
			log.info("token====" + token);
			
			if ("true".equals(success) && "SUCCESS".equalsIgnoreCase(msg)) {
				log.info("请求绑卡接口成功===================");
				
				XJYCoinBindCard xjyCoinBindCard = topupPayChannelBusiness.getXJYCoinBindCardByBankCard(bankCard);
				
				if(null == xjyCoinBindCard) {
					XJYCoinBindCard xjyCoinBindCard1 = new XJYCoinBindCard();
					xjyCoinBindCard1.setBankCard(bankCard);
					xjyCoinBindCard1.setToken(token);

					try {
						topupPayChannelBusiness.createXJYCoinBindCard(xjyCoinBindCard1);
					} catch (Exception e) {
						log.error("保存用户绑卡信息失败=====");
						maps.put("resp_code", "failed");
						maps.put("channel_type", "jf");
						maps.put("resp_message", "保存用户绑卡信息失败");
						return maps;
					}
					log.info("保存用户绑卡信息成功=====");
				}else {
					xjyCoinBindCard.setBankCard(bankCard);
					xjyCoinBindCard.setToken(token);
					try {
						topupPayChannelBusiness.createXJYCoinBindCard(xjyCoinBindCard);
					} catch (Exception e) {
						log.error("保存用户绑卡信息失败=====");
						maps.put("resp_code", "failed");
						maps.put("channel_type", "jf");
						maps.put("resp_message", "保存用户绑卡信息失败");
						return maps;
					}
					log.info("保存用户再次绑卡信息成功=====");
				}
				

				
				
				/*map.put("resp_code", "success");
				map.put("channel_type", "jf");
				map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/cjbindcardsuccess");
				return map;*/
				
				map.put("resp_code", "success");
				map.put("channel_type", "jf");
				map.put("redirect_url",
						ipAddress + "/v1.0/paymentchannel/topup/toxjycoinpaymessage?&ordercode=" + ordercode + "&ipAddress="+ ipAddress);
				return map;
				
			}else {
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/cjbindcarderror");
				return map;
			}
			
		} catch (Exception e) {
			log.error("请求绑卡接口有误===" + e);
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "亲，请求出错啦！请重新发起交易");
			return maps;
		}
		
		
	}

	// 消费短信接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/xjycoin/consumesms")
	public @ResponseBody Object xjycoinsms(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "ordercode") String ordercode) throws Exception {
		log.info("开始进入消费短信接口======");
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询订单信息出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "没有该订单信息");
			return maps;
		}
		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费用
		String extraFee = resultObj.getString("extraFee");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		String amount = resultObj.getString("amount");
		
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询默认结算卡出错");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "查询默认结算卡有误");
			return maps;
		}

		if (resultObj.isNullObject()) {

			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}

		String cardNo = resultObj.getString("cardNo");
		
		XJYCoinRegister xjyCoinRegisterByBankCard = topupPayChannelBusiness.getXJYCoinRegisterByBankCard(cardNo);
		
		XJYCoinBindCard xjyCoinBindCardByBankCard = topupPayChannelBusiness.getXJYCoinBindCardByBankCard(bankCard);
		String token = xjyCoinBindCardByBankCard.getToken();
		
		String Amount = new BigDecimal(amount).multiply(new BigDecimal("100")).setScale(0).toString();
		
		Map<String, String> paramsMap = new HashMap<String, String>();

		paramsMap.put("appId", appId);
		paramsMap.put("channelType", channelType);
		paramsMap.put("version", version);
		paramsMap.put("orderId", ordercode);//订单号
		paramsMap.put("txnTime", DateUtil.getyyyyMMddHHmmssDateFormat(new Date()));
		paramsMap.put("body", "充值缴费");//商品描述
		paramsMap.put("token", token);//交易令牌
		paramsMap.put("txnAmt", Amount);//交易金额
		//paramsMap.put("userFee", );//商户手续费
		paramsMap.put("insCode", xjyCoinRegisterByBankCard.getInsCode());//入网编号
		
		Map<String, String> reqData = new HashMap<String, String>();
		try {
			reqData.put("data", Base64Util.encode(
					KeyGenerator.encryptByPublicKey(JSON.toJSONString(paramsMap).getBytes(UTF_8), PublicKey)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		
		String requestUrl = String.format(smsUrl+"/"+channelType+"/"+appId, channelType, appId);
		String jsonString;
		try {
			jsonString = PlatService.postAsString(reqData, requestUrl, UTF_8);
			JSONObject json = jsonObject.fromObject(jsonString);
			String success = json.getString("success");
			String msg = json.getString("msg");
			JSONObject attributes = json.getJSONObject("attributes");
			//String tradeNo = ;
			//String queryId = ;
			log.info("json====" + json);
			log.info("success====" + success);
			log.info("msg====" + msg);
			log.info("attributes====" + attributes);
			
			if ("true".equals(success) && "SUCCESS".equalsIgnoreCase(msg)) {
				
				maps.put("resp_code", "success");
				maps.put("channel_type", "jf");
				maps.put("tradeNo", attributes.getString("tradeNo"));
				maps.put("queryId", attributes.getString("queryId"));
				return maps;
				
			}else {
				maps.put("resp_code", "failed");
				maps.put("channel_type", "jf");
				maps.put("resp_message", "亲，请求出错啦！请重新发起交易");
				return maps;
			}
			
		} catch (Exception e) {
			log.error("请求消费短信接口有误===" + e);
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "亲，请求出错啦！请重新发起交易");
			return maps;
		}
		
		
	}

	// 确认支付接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/xjycoin/consume")
	public @ResponseBody Object xjycoinConsume(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "queryId") String queryId,
			@RequestParam(value = "smsCode") String smsCode
			) throws Exception {

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		log.info("开始进入支付接口========================");
		Map<String, String> maps = new HashMap<String, String>();
		
		Map<String, String> paramsMap = new HashMap<String, String>();

		paramsMap.put("appId", appId);
		paramsMap.put("channelType", channelType);
		paramsMap.put("version", version);
		paramsMap.put("orderId", ordercode);//订单号
		paramsMap.put("txnTime", DateUtil.getyyyyMMddHHmmssDateFormat(new Date()));
		paramsMap.put("queryId", queryId);//交易流水号
		paramsMap.put("body", "充值缴费");//商品描述
		paramsMap.put("smsCode", smsCode);//短信验证码
		paramsMap.put("backUrl", ipAddress + "/v1.0/paymentchannel/topup/xjycoin/notify_call");//通知回调地址
		
		Map<String, String> reqData = new HashMap<String, String>();
		try {
			reqData.put("data", Base64Util.encode(
					KeyGenerator.encryptByPublicKey(JSON.toJSONString(paramsMap).getBytes(UTF_8), PublicKey)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		String requestUrl = String.format(consumeUrl+"/"+channelType+"/"+appId, channelType, appId);
		String jsonString;
		JSONObject jsonObject = null;
		try {
			jsonString = PlatService.postAsString(reqData, requestUrl, UTF_8);
			JSONObject json = jsonObject.fromObject(jsonString);
			String success = json.getString("success");
			String msg = json.getString("msg");
			//JSONObject attributes = json.getJSONObject("attributes");
			//String tradeNo = ;
			//String queryId = ;
			log.info("json====" + json);
			log.info("success====" + success);
			log.info("msg====" + msg);
			//log.info("attributes====" + attributes);
			
			//"true".equals(success) && 
			
			if ("SUCCESS".equalsIgnoreCase(msg) || "处理中".equals(msg)) {
				
				maps.put("resp_code", "success");
				maps.put("channel_type", "jf");
				maps.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/sdjpaysuccess");
				return maps;
				
			}else {
				maps.put("resp_code", "failed");
				maps.put("channel_type", "jf");
				maps.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/sdjpayerror");
				return maps;
			}
			
		} catch (Exception e) {
			log.error("请求消费短信接口有误===" + e);
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/sdjpayerror");
			return maps;
		}
		

	}

	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/xjycoin/turntobindcard")
	public @ResponseBody Object xjyCoinTurnToBindCard(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "expiredTime", required = false) String expiredTime,
			@RequestParam(value = "securityCode", required = false) String securityCode,
			@RequestParam(value = "cardName", required = false) String cardName,
			@RequestParam(value = "cardtype", required = false) String cardtype,
			@RequestParam(value = "bankCard", required = false) String bankCard) throws Exception {

		Map<String, String> map = new HashMap<String, String>();

		map.put("resp_code", "success");
		map.put("channel_type", "jf");
		map.put("redirect_url",
				ipAddress + "/v1.0/paymentchannel/topup/toxjycoinbindcard?&ordercode=" + ordercode + "&ipAddress="
						+ ipAddress + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardName, UTF_8.displayName())
						+ "&cardtype=" + URLEncoder.encode(cardtype, UTF_8.displayName()) + "&expiredTime=" + expiredTime
						+ "&securityCode=" + securityCode);
		return map;

	}

	
	
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/xjycoin/turntopaypage")
	public @ResponseBody Object xjyCoinTurnToPayPage(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "ordercode") String ordercode
			) throws Exception {

		Map<String, String> map = new HashMap<String, String>();

		map.put("resp_code", "success");
		map.put("channel_type", "jf");
		map.put("redirect_url",
				ipAddress + "/v1.0/paymentchannel/topup/toxjycoinpaymessage?&ordercode=" + ordercode + "&ipAddress="+ ipAddress);
		return map;

	}
	
	
	
	
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/toxjycoinbankinfo")
	public String toxjycoinbankinfo(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		String bankName = request.getParameter("bankName");// 结算卡银行名称
		String bankNo = request.getParameter("bankNo");// 结算卡卡号
		String amount = request.getParameter("amount");
		String ordercode = request.getParameter("ordercode");
		String cardType = request.getParameter("cardType");
		String ipAddress = request.getParameter("ipAddress");
		String bankCard = request.getParameter("bankCard");
		String cardName = request.getParameter("cardName");
		String cardtype = request.getParameter("cardtype");
		String expiredTime = request.getParameter("expiredTime");
		String securityCode = request.getParameter("securityCode");
		String isRegister = request.getParameter("isRegister");

		model.addAttribute("bankName", bankName);
		model.addAttribute("bankNo", bankNo);
		model.addAttribute("amount", amount);
		model.addAttribute("ordercode", ordercode);
		model.addAttribute("cardType", cardType);
		model.addAttribute("ipAddress", ipAddress);
		model.addAttribute("bankCard", bankCard);
		model.addAttribute("cardName", cardName);
		model.addAttribute("cardtype", cardtype);
		model.addAttribute("expiredTime", expiredTime);
		model.addAttribute("securityCode", securityCode);
		model.addAttribute("isRegister", isRegister);

		return "xjycoinbankinfo";
	}

	
	
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/toxjycoinbindcard")
	public String toxjyCoinBindCard(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		String ordercode = request.getParameter("ordercode");
		String ipAddress = request.getParameter("ipAddress");
		String cardName = request.getParameter("cardName");
		String cardtype = request.getParameter("cardtype");
		String expiredTime = request.getParameter("expiredTime");
		String securityCode = request.getParameter("securityCode");
		String bankCard = request.getParameter("bankCard");

		model.addAttribute("ordercode", ordercode);
		model.addAttribute("ipAddress", ipAddress);
		model.addAttribute("cardName", cardName);
		model.addAttribute("cardtype", cardtype);
		model.addAttribute("expiredTime", expiredTime);
		model.addAttribute("securityCode", securityCode);
		model.addAttribute("bankCard", bankCard);

		return "xjycoinbindcard";
	}

	
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/toxjycoinpaymessage")
	public String toxjyCoinPayMessage(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		String ordercode = request.getParameter("ordercode");
		String ipAddress = request.getParameter("ipAddress");

		model.addAttribute("ordercode", ordercode);
		model.addAttribute("ipAddress", ipAddress);

		return "xjycoinpaymessage";
	}
	
	
	
	
	
	// 交易异步通知
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/xjycoin/notify_call")
	public void cjNotifyCallback(HttpServletRequest request, HttpServletResponse response

	) throws Exception {

		log.info("支付异步通知进来了");

		response.setHeader("Content-type", "text/html;charset=UTF-8");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        Map<String, String[]> requestMap = request.getParameterMap();
        Iterator<Entry<String, String[]>> it = requestMap.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, String[]> entry = it.next();
            if (entry.getValue().length == 1) {
                paramMap.put(entry.getKey(), entry.getValue()[0]);
            } else {
                String[] values = entry.getValue();
                String value = "";
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
                paramMap.put(entry.getKey(), value);
            }
        }
        StringBuilder buffer = new StringBuilder();
        for (Entry<String, Object> entry : paramMap.entrySet()) {
            buffer.append(entry.getKey() + "|" + entry.getValue()).append("\r\n");
        }
        String data = request.getParameter("data");
        String signature = request.getParameter("signature");
        //String publicKey =  QuickPaySDKConfig.getConfig().getT0PubicKey();
        byte[] decrytData;
        try {
            decrytData = KeyGenerator.decryptByPublicKey(Base64Util.decode(data), PublicKey);
            boolean verify = KeyGenerator.verify(decrytData, PublicKey, signature);
            String rspString = new String(decrytData, UTF_8);
            com.alibaba.fastjson.JSONObject rspData = JSON.parseObject(rspString);
            if(verify){
            	
            	String orderId = rspData.getString("orderId");
                String payStatus = rspData.getString("payStatus");
                String settleStatus = rspData.getString("settleStatus");
                String queryId = rspData.getString("queryId");
                String tradeNo = rspData.getString("tradeNo");
                
                log.info("订单号   orderId===="+orderId);
                log.info("交易状态   payStatus===="+payStatus);
                log.info("出款状态   settleStatus====="+settleStatus);
                log.info("查询流水号   queryId====="+queryId);
                log.info("交易跟踪号   tradeNo====="+tradeNo);

                
                try {

    				log.info("交易： 订单结果异步通知===================");
    				if("Y".equals(payStatus)&&"Y".equals(settleStatus)){ // 订单已支付;

    					// 1、检查Amount和商户系统的订单金额是否一致
    					// 2、订单支付成功的业务逻辑处理请在本处增加（订单通知可能存在多次通知的情况，需要做多次通知的兼容处理）；
    					// 3、返回响应内容
    					
    					response.getWriter().write("success");// 回调成功
    					
    					synchronized (this) {
    						// **更新订单状态*//*
    						// **调用下单，需要得到用户的订单信息*//*
    						RestTemplate restTemplate = new RestTemplate();

    						URI uri = util.getServiceUrl("transactionclear", "error url request!");
    						String url = uri.toString() + "/v1.0/transactionclear/payment/update";

    						// **根据的用户手机号码查询用户的基本信息*//*
    						MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
    						requestEntity.add("status", "1");
    						requestEntity.add("third_code", queryId);
    						requestEntity.add("order_code", orderId);
    						String result = restTemplate.postForObject(url, requestEntity, String.class);

    						log.info("订单状态修改成功===================");

    						/*// **判断是否有外放的通道的处理， 如果有那么继续回调外放哦*//*
    						uri = util.getServiceUrl("transactionclear", "error url request!");
    						url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";

    						requestEntity = new LinkedMultiValueMap<String, String>();
    						requestEntity.add("order_code", orderId);
    						result = restTemplate.postForObject(url, requestEntity, String.class);

    						JSONObject jsonObject = JSONObject.fromObject(result);
    						JSONObject resultObj = jsonObject.getJSONObject("result");
    						String outMerOrdercode = resultObj.getString("outMerOrdercode");
    						String orderdesc = resultObj.getString("desc");
    						String phone = resultObj.getString("phone");
    						String tranamount = resultObj.getString("amount");
    						String channelTag = resultObj.getString("channelTag");
    						String notifyURL = resultObj.getString("outNotifyUrl");
    						if (outMerOrdercode != null && !outMerOrdercode.equalsIgnoreCase("")) {
    							uri = util.getServiceUrl("channel", "error url request!");
    							url = uri.toString() + "/v1.0/channel/callback/yilian/notify_call";
    							requestEntity = new LinkedMultiValueMap<String, String>();
    							requestEntity.add("merchant_no", phone);
    							requestEntity.add("amount", tranamount);
    							requestEntity.add("channel_tag", channelTag);
    							requestEntity.add("order_desc", URLEncoder.encode(orderdesc, "UTF-8"));
    							requestEntity.add("order_code", outMerOrdercode);
    							requestEntity.add("sys_order", orderId);
    							requestEntity.add("notify_url", URLEncoder.encode(notifyURL, "UTF-8"));
    							result = restTemplate.postForObject(url, requestEntity, String.class);
    						}*/

    						log.info("订单已支付!");
    						
    					}
    				} else {
    					// 1、订单支付失败的业务逻辑处理请在本处增加（订单通知可能存在多次通知的情况，需要做多次通知的兼容处理，避免成功后又修改为失败）；
    					// 2、返回响应内容

    					log.info("订单支付失败!");
    				}
    			} catch (Exception e) {
    				log.error(e.getMessage());
    			}
    			log.info("-----处理完成----");
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
       

	}

}